import router from 'umi/router';
import { message } from 'antd';
import { getList, deleteBatch, add,edit } from './services';

export default {
  namespace: 'domainGroup',
  state: {
    loading: false,
    pageNum: 1,
    pageSize: 10,
    total: 10,
    list: [],
  },

  effects: {
    *getList({ payload }, { call, put }) {
      try {
        yield put({
          type: 'changeLoading',
          payload: true,
        });
        const res = yield call(getList, payload);
        yield put({
          type: 'save',
          payload: {
            pageNum: res.pageNum,
            pageSize: res.pageSize,
            total: res.total,
            list: res.pageData,
          },
        });
      } catch (e) {
        message.error(e.message);
      } finally {
        yield put({
          type: 'changeLoading',
          payload: false,
        });
      }
    },

    *add({ payload,callback }, { call, put,select }) {
      try {
        yield call(add, payload);
        const total = yield select(state => state.domainGroup.total);
        const pageSize = yield select(state => state.domainGroup.pageSize);
        const pageNum = Math.ceil((total + 1) / pageSize);
        message.info('添加成功');
        callback(pageNum,pageSize);
      } catch (e) {
        message.error(e.message);
      }
    },

    *edit({ payload,callback }, { call, put,select }) {
      try {
        yield call(edit, payload);
        const pageSize = yield select(state => state.domainGroup.pageSize);
        const pageNum = yield select(state => state.domainGroup.pageNum);
        message.info('修改成功');
        callback(pageNum,pageSize);
      } catch (e) {
        message.error(e.message);
      }
    },

    *delete({ payload, callback }, { call, put, select }) {
      try {
        yield call(deleteBatch, payload);
        const pageSize = yield select(state => state.domainGroup.pageSize);
        const preTotal = yield select(state => state.domainGroup.total);
        const curPage = yield select(state => state.domainGroup.pageNum);
        let curTotal = preTotal - payload.ids.length;
        const lastPage = Math.ceil(curTotal / 10);
        let pageNum = Math.min.apply(null, [curPage, lastPage]);
        callback(pageNum, pageSize);
        message.info('操作成功');
      } catch (e) {
        message.error(e.message);
      }
    },
  },

  reducers: {
    changeLoading(state, { payload }) {
      return {
        ...state,
        loading: payload,
      };
    },

    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
